package com.sc.test.utils;


import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

/**
 * Created by Shen Chao on 2018-01-10-010 下午 15:11.
 */

public class RxBus {
    public static volatile RxBus rxBus;
    private final Subject<Object> bus;

    private RxBus() {
        bus = PublishSubject.create().toSerialized();
    }

    public static RxBus getInstance() {
        if (rxBus == null) {
            synchronized (RxBus.class) {
                if (rxBus == null) {
                    rxBus = new RxBus();
                }
            }
        }
        return rxBus;
    }

    /**
     * 发送时间
     *
     * @param o
     */
    public void post(@NonNull Object o) {
        bus.onNext(o);
    }

    /**
     * 类型转换
     *
     * @param eventType
     * @param <T>
     * @return
     */
    public <T> Observable<T> toObservable(final Class<T> eventType) {
        return bus.ofType(eventType);
    }

    /**
     * 是否有订阅
     *
     * @return
     */
    public boolean hasObservers() {
        return bus.hasObservers();
    }

    /**
     * 会将所有由mBus生成的Observable都置completed状态,后续的所有消息都收不到了
     */
    //todo
    public void unregisterAll() {
        bus.onComplete();
    }
}
